/**
 *  This file is part of MunchLevel.
 *
 *  MunchLevel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MunchLevel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MunchLevel.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.munchlevel.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.gandulf.guilib.util.Debug;
import com.munchlevel.BaseGameActivity;
import com.munchlevel.FightActivity;
import com.munchlevel.MunchLevelApplication;
import com.munchlevel.MyPreferenceActivity;
import com.munchlevel.R;
import com.munchlevel.data.GameInfo;
import com.munchlevel.data.PlayerInfo;
import com.munchlevel.view.PlayerLayout;
import com.munchlevel.view.listener.OnPlayerChangedListener;

/**
 * @author Ganymede
 * 
 */
public class PlayerFragment extends Fragment implements OnClickListener, OnSharedPreferenceChangeListener {

	protected static final int REQUEST_PICTURE = 1;

	protected static final int ACTION_DELETE_PICTURE = 6;

	private OnPlayerChangedListener onPlayerChangedListener;

	private PlayerLayout playerLayout;

	private PlayerInfo playerInfo;

	private boolean singlePlayer;

	/**
	 * 
	 */
	private PlayerFragment() {
		setRetainInstance(true);
	}

	/**
	 * 
	 */
	public PlayerFragment(PlayerInfo playerInfo, boolean singlePlayer) {
		this();
		this.playerInfo = playerInfo;
		this.singlePlayer = singlePlayer;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
	 * android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		playerLayout = (PlayerLayout) inflater.inflate(R.layout.player, container, false);
		playerLayout.setPlayerFragment(this);
		playerLayout.setOnPlayerChangedListener(onPlayerChangedListener);
		playerLayout.setPlayerInfo(playerInfo);

		if (singlePlayer
				&& getActivity().getWindowManager().getDefaultDisplay().getWidth() > getActivity().getWindowManager()
						.getDefaultDisplay().getHeight()) {
			playerLayout.setOrientation(Configuration.ORIENTATION_LANDSCAPE);
		} else {
			playerLayout.setOrientation(Configuration.ORIENTATION_PORTRAIT);
		}

		onSharedPreferenceChanged(PreferenceManager.getDefaultSharedPreferences(getActivity()), null);

		return playerLayout;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onViewCreated(android.view.View,
	 * android.os.Bundle)
	 */
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

	}

	public PlayerInfo getPlayerInfo() {
		return playerInfo;
	}

	public void setPlayerInfo(PlayerInfo playerInfo) {
		this.playerInfo = playerInfo;
		if (playerLayout != null) {
			playerLayout.setPlayerInfo(playerInfo);
		}
	}

	public void notifyDataSetChanged() {
		if (playerLayout != null) {
			playerLayout.setPlayerInfo(playerInfo);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		// init profile picture
		ImageView profilePicture = (ImageView) playerLayout.findViewById(R.id.iv_profile);
		registerForContextMenu(profilePicture);
		profilePicture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				openCamera();
			}
		});

		playerLayout.setOnClickListener(this);

		restorePlayer();

		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

		if (v.getId() == R.id.iv_profile) {
			if (playerInfo.getProfile() != null) {
				menu.add(0, ACTION_DELETE_PICTURE, 0, R.string.btn_delete_picture).setIcon(
						android.R.drawable.ic_menu_delete);
			}
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == ACTION_DELETE_PICTURE) {

			// delete profile picture
			File profileFile = new File(getActivity().getCacheDir(), "profile_" + playerInfo.getIndex() + ".jpg");
			if (profileFile.exists())
				profileFile.delete();

			playerInfo.setProfile(null);
			return true;
		}
		return super.onContextItemSelected(item);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		if (v instanceof PlayerLayout && v.getTag() instanceof Integer) {
			startFight();
		}
	}

	public void startFight() {
		getGameInfo().setSelectedPlayer(playerInfo.getIndex());
		startActivityForResult(new Intent(getActivity(), FightActivity.class), BaseGameActivity.REQUEST_FIGHT);
	}

	protected GameInfo getGameInfo() {
		return MunchLevelApplication.getInstance().getGameInfo();
	}

	public void openCamera() {
		// gameInfo.setSelectedPlayer(player);
		Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(camera, REQUEST_PICTURE);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_PICTURE:

			if (resultCode == Activity.RESULT_OK) {
				// Display image received on the view
				Bundle b = data.getExtras(); // Kept as a Bundle to check for
												// other things in my actual
												// code
				Bitmap pic = (Bitmap) b.get("data");

				if (pic != null) { // Display your image in an ImageView in your
									// layout (if you want to test it)

					Debug.verbose("setting picture for player" + playerInfo);
					playerLayout.setProfilePicture(pic);
					storePlayerProfile();
				}
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		storePlayer();
		super.onDestroy();
	}

	private void storePlayerProfile() {
		Bitmap profileBitmap = playerInfo.getProfile();
		if (profileBitmap != null) {

			FileOutputStream fos = null;
			try {
				File file = new File(getActivity().getCacheDir(), "profile_" + playerInfo.getIndex() + ".jpg");
				fos = new FileOutputStream(file);
				profileBitmap.compress(Bitmap.CompressFormat.JPEG /* FileType */, 70 /* Ratio */, fos);
			} catch (FileNotFoundException e) {
				Debug.error(e);
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						Debug.error(e);
					}
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onConfigurationChanged(android.content
	 * .res.Configuration)
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		applyTheme();
	}

	public boolean applyTheme() {
		boolean ok = true;
		if (playerLayout != null) {

			if (singlePlayer
					&& getActivity().getWindowManager().getDefaultDisplay().getWidth() > getActivity()
							.getWindowManager().getDefaultDisplay().getHeight()) {
				playerLayout.setOrientation(Configuration.ORIENTATION_LANDSCAPE);
			} else {
				playerLayout.setOrientation(Configuration.ORIENTATION_PORTRAIT);
			}

			ok = playerLayout.updateBackground();
		}
		return ok;
	}

	private void storePlayer() {
		if (playerInfo != null) {
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());

			Editor edit = pref.edit();
			edit.putString(PlayerInfo.NAME + playerInfo.getIndex(), playerInfo.getName());
			edit.commit();
		}
	}

	private void restorePlayer() {
		if (playerInfo != null) {
			File file = new File(getActivity().getCacheDir(), "profile_" + playerInfo.getIndex() + ".jpg");
			if (file.exists()) {
				Debug.verbose("restoring picture for player " + playerInfo.getIndex());
				Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
				playerInfo.setProfile(bitmap);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#
	 * onSharedPreferenceChanged(android.content.SharedPreferences,
	 * java.lang.String)
	 */
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		if (playerLayout != null) {
			if (key == null || MyPreferenceActivity.KEY_TOOLTIPS.equals(key)) {
				boolean visible = sharedPreferences.getBoolean(MyPreferenceActivity.KEY_TOOLTIPS, true);
				// tooltip are only visible on the first screen

				Debug.verbose(playerLayout + ":" + playerInfo);
				playerLayout.setTooltipVisibility(playerInfo.getIndex() == 0 && visible);
			}

			playerLayout.onSharedPreferenceChanged(sharedPreferences, key);
		}
	}

	public OnPlayerChangedListener getOnPlayerChangedListener() {
		return onPlayerChangedListener;
	}

	public void setOnPlayerChangedListener(OnPlayerChangedListener onPlayerChangedListener) {
		this.onPlayerChangedListener = onPlayerChangedListener;
		if (playerLayout != null)
			playerLayout.setOnPlayerChangedListener(onPlayerChangedListener);
	}

}
